package ee.serge.util;

import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.SimplePanel;

public class RatingPanel extends FocusPanel {

   private SimplePanel upper;
   private HandlerRegistration mouseMoveRegistration;
   private int value;
   
   /**
    * 
    * @param value  between 1 and 5
    */
   public RatingPanel(float value, boolean isEditable) {
      setSize("100px", "19px");
      addStyleName("rating-background");
      
      upper = new SimplePanel();
      String width = String.valueOf((int)(value * 20)) + "px";
      upper.setSize(width, "19px");
      upper.addStyleName("rating-foreground");
      add(upper);
      this.value = (int)value;
      
      if (isEditable) {
         addMouseOverHandler(new MouseOver());
         addMouseOutHandler(new MouseOut());
      }
      
   }
   
   private class MouseOver implements MouseOverHandler {

      @Override
      public void onMouseOver(MouseOverEvent event) {
         mouseMoveRegistration = Event.addNativePreviewHandler(new NativePreviewHandler() {
            @Override
            public void onPreviewNativeEvent(NativePreviewEvent event) {
               switch (event.getTypeInt()) {
               case Event.ONMOUSEMOVE:
                  int x = (((event.getNativeEvent().getClientX() - RatingPanel.this.getAbsoluteLeft()) / 20) + 1);
                  if (x > 5) x = 5;
                  value = x;
                  upper.setSize(x * 20 + "px", "19px");
               }
            }
         });
      }
      
   }
   
   private class MouseOut implements MouseOutHandler {

      @Override
      public void onMouseOut(MouseOutEvent event) {
         mouseMoveRegistration.removeHandler();
         mouseMoveRegistration = null;
      }
      
   }
   
   public int getValue() {
      return value;
   }
   
}
